package com.wcz.code.作业调度;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Date;

import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wcz.code.util.Common;

/**
 * 
 * 计划任务
 * @author 伪尘子
 *
 * 2012-6-20
 */
public class MyJob implements Job{
	
    private static Logger _log = LoggerFactory.getLogger(MyJob.class);
	
	/**
	 * 任务执行内容
	 */
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		
		
		String date=Common.getDate("yyyy-MM-dd hh:mm:ss:SSS");
		System.out.println("This time is "+date);
		_log.info("This time is "+date);
		
	}
	
	/**
	 * @param args
	 * @throws SchedulerException 
	 */
	public static void main(String[] args) throws SchedulerException {
		//挂起任务
		System.setProperty("myworkdir", Common.getClassPath());
		MyScheduler.run();
	}
	
}

/**
 * 注册任务到Scheduler
 * @author 伪尘子
 *
 * 2012-6-20
 */
class MyScheduler{
	
	static void run() throws SchedulerException{
		
		SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = sf.getScheduler();
        
        // define the job and tie it to our HelloJob class
        JobDetail job = newJob(MyJob.class)
            .withIdentity("job1", "group1")
            .build();
        
        // Trigger the job to run on the next round minute
        Trigger trigger = newTrigger()
            .withIdentity("trigger1", "group1")
            .startAt(Common.changeDate(new Date(), "{\"second\":"+(Common.getDateFiled(null, "second")+10)+",\"millisecond\":0}"))
            .build();
        
        // Tell quartz to schedule the job using our trigger
        sched.scheduleJob(job, trigger);

        // Start up the scheduler (nothing can actually run until the 
        // scheduler has been started)
        sched.start();
        
        try {
            // wait 65 seconds to show job
            Thread.sleep(12L * 1000L); 
            // executing...
        } catch (Exception e) {
        }
        sched.shutdown(true);
	}
}

